//
//  JYComposeViewController.swift
//  WeiBoDemo
//
//  Created by 万佳阳 on 16/8/5.
//  Copyright © 2016年 JYWan. All rights reserved.
//

import UIKit
import SVProgressHUD

class JYComposeViewController: UIViewController {
    // MARK:- 懒加载属性
    private lazy var titleView : JYComposeTitleView = JYComposeTitleView()
    private lazy var images : [UIImage] = [UIImage]()
    private lazy var emoticonVc : EmoticonController = EmoticonController {[weak self] (emoticon) in
        self?.textView.insertEmoticon(emoticon)
        self?.textViewDidChange(self!.textView)
    }
    
    // MARK:- 控件属性
    @IBOutlet weak var textView: JYComposeTextView!
    @IBOutlet weak var picPickerView: JYPicPickerView!
    
    // MARK:- 约束属性
    @IBOutlet weak var toolbarBottomCons: NSLayoutConstraint!
    @IBOutlet weak var picPickerViewHCons: NSLayoutConstraint!
    
    // MARK:- 系统回调函数
    override func viewDidLoad() {
        super.viewDidLoad()

        //设置导航栏 
        setupNavigationBar()
        
        //监听通知
        setupNotifications()
        
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        textView.becomeFirstResponder()
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

}

// MARK:- 设置UI界面
extension JYComposeViewController {
    private func setupNavigationBar() {
        //设置左右的item
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: #selector(JYComposeViewController.closeItemClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .Plain, target: self, action: #selector(JYComposeViewController.sendItemClick))
        navigationItem.rightBarButtonItem?.enabled = false
        
        //设置标题
        titleView.frame = CGRect(x: 0, y: 0, width: 100, height: 40)
        navigationItem.titleView = titleView
    }
    
    ///监听通知
    private func setupNotifications() {
        //监听键盘弹出
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(JYComposeViewController.KeyboardWillChangeFrame(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        //监听添加照片按钮点击
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(JYComposeViewController.addPhotoClick), name: picPickerAddPhotoNote, object: nil)
        
        //监听删除按钮点击
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(JYComposeViewController.closePhotoClick(_:)), name: picPickerClosePhotoNote, object: nil)
    }
}

// MARK:- 添加照片和删除照片的事件
extension JYComposeViewController {
    @objc private func addPhotoClick() {
        //判断照片源是否可用 
        if !UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary) {
            return
        }
        
        //创建照片选择控制器
        let picker = UIImagePickerController()
        
        //设置照片源
        picker.sourceType = .PhotoLibrary
        
        //设置代理
        picker.delegate = self
        
        //弹出控制器
        presentViewController(picker, animated: true, completion: nil)
        
    }
    
    @objc private func closePhotoClick(note : NSNotification) {
        //获取要删除的image
        guard let image = note.object as? UIImage else {
            return
        }
        
        //获取对应索引
        guard let index = images.indexOf(image) else {
            return
        }
        
        //将图片从数组中删除
        images.removeAtIndex(index)
        
        picPickerView.images = images
    }
}

// MARK:- UIImagePickerController代理方法
extension JYComposeViewController : UINavigationControllerDelegate, UIImagePickerControllerDelegate {
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        //获取照片
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        
        //添加到数组中
        images.append(image)
        
        picPickerView.images = images
        
        dismissViewControllerAnimated(true, completion: nil)
    }
  
}

// MARK:- 事件监听
extension JYComposeViewController {
    @objc private func closeItemClick() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func sendItemClick() {
        //退出键盘
        textView.resignFirstResponder()
        
        //获取发送微博正文
        let statusText = textView.getEmoticonString()
        
        //定义回调闭包
        let finishedCallBack =  { (isSuccess : Bool) in
            if !isSuccess {
                SVProgressHUD.showErrorWithStatus("发送微博失败")
                return
            }
            
            SVProgressHUD.showSuccessWithStatus("发送微博成功")
            self.dismissViewControllerAnimated(true, completion: nil)
        }
        
        
        //获取用户选中的图片
        if let image = images.first {
            //发送微博
            NetworkTools.shareInstance.sendStatus(statusText, image: image, isSuccess:  finishedCallBack)
        } else {
            //发送微博
            NetworkTools.shareInstance.sendStatus(statusText, isSuccess: finishedCallBack)
            
        }
        
    }
    
    @objc private func KeyboardWillChangeFrame(note : NSNotification) {
        //动画执行事件
        let duration = note.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
        
        //键盘最终Y值
        let endFrame = (note.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        let y = endFrame.origin.y
        
        //计算工具条的底部间距
        toolbarBottomCons.constant = UIScreen.mainScreen().bounds.height - y
        
        //执行动画
        UIView.animateWithDuration(duration) { 
            self.view.layoutIfNeeded()
        }
    }
    
    @IBAction func picPickerBtnClick() {
        //退出键盘
        textView.resignFirstResponder()
        
        //设置picPickerView的高度约束
        picPickerViewHCons.constant = UIScreen.mainScreen().bounds.height * 0.65
        
        //执行动画
        UIView.animateWithDuration(0.5) { 
            self.view.layoutIfNeeded()
        }
        
    }
    
    @IBAction func emoticonBtnClick() {
        //退出键盘
        textView.resignFirstResponder()
        
        //切换键盘
        textView.inputView = textView.inputView != nil ? nil : emoticonVc.view
        
        //弹出键盘
        textView.becomeFirstResponder()
    }
    
}

// MARK:- textView代理
extension JYComposeViewController : UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        self.textView.placeholderLabel.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        textView.resignFirstResponder()
    }
}
